<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
        <div class="aside-header">
          <span>对话列表</span>
          <el-button
              type="primary"
              size="small"
              :icon="Plus"
              @click="createNewChat"
              :loading="creating"
          >
            新对话
          </el-button>
        </div>
        <div class="conversation-list">
          <div
              v-for="id in conversationIds"
              :key="id"
              :class="['conversation-item', { active: currentChatId === id }]"
          >
            <div class="conversation-content" @click="switchConversation(id)">
              {{ chatNames[id] || '新建对话' }}
            </div>
            <div class="conversation-actions">
              <el-button
                  type="text"
                  :icon="Edit"
                  @click="showEditDialog(id)"
              />
              <el-button
                  type="text"
                  :icon="Delete"
                  class="delete-btn"
                  @click="showDeleteConfirm(id)"
              />
            </div>
          </div>
        </div>
        <el-dialog
            v-model="editDialogVisible"
            title="修改对话名称"
            width="30%"
        >
          <el-input v-model="editingName" placeholder="请输入对话名称" />
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="editDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveConversationName">
                确认
              </el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 删除确认对话框 -->
        <el-dialog
            v-model="deleteDialogVisible"
            title="确认删除"
            width="30%"
        >
          <span>确定要删除这个对话吗？此操作不可恢复。</span>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="deleteDialogVisible = false">取消</el-button>
              <el-button type="danger" @click="confirmDelete" :loading="deleting">
                确认删除
              </el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 用户信息对话框 -->
        <el-dialog
            v-model="userInfoVisible"
            title="个人信息"
            width="30%"
        >
          <div class="user-info-content" v-if="userInfo">
            <el-form :model="userInfo" label-width="80px" v-if="!isEditing">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="用户ID">{{ userInfo.id }}</el-descriptions-item>
                <el-descriptions-item label="用户名">{{ userInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="账号">{{ userInfo.account }}</el-descriptions-item>
              </el-descriptions>
            </el-form>

            <!-- 编辑表单 -->
            <el-form
                v-else
                :model="editForm"
                label-width="80px"
                :rules="rules"
                ref="editFormRef"
            >
              <el-form-item label="用户名" prop="name">
                <el-input v-model="editForm.name" />
              </el-form-item>
              <el-form-item label="账号" prop="account">
                <el-input v-model="editForm.account" />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="editForm.password" type="password" show-password />
              </el-form-item>
            </el-form>
          </div>

          <template #footer>
            <span class="dialog-footer">
              <template v-if="!isEditing">
                <el-button type="danger" @click="showDeleteUserConfirm">删除账号</el-button>
                <el-button type="primary" @click="startEdit">修改信息</el-button>
                <el-button @click="userInfoVisible = false">关闭</el-button>
              </template>
              <template v-else>
                <el-button @click="cancelEdit">取消</el-button>
                <el-button type="primary" @click="saveUserInfo" :loading="saving">
                  保存
                </el-button>
              </template>
            </span>
          </template>
        </el-dialog>

        <!-- 删除账号确认对话框 -->
        <el-dialog
            v-model="deleteConfirmVisible"
            title="确认删除账号"
            width="30%"
        >
          <div class="delete-confirm-content">
            <p>确定要删除您的账号吗？此操作不可恢复！</p>
            <p class="warning">删除账号后，所有相关数据将被永久删除。</p>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="deleteConfirmVisible = false">取消</el-button>
              <el-button type="danger" @click="confirmDeleteUser" :loading="deletingUser">
                确认删除
              </el-button>
            </span>
          </template>
        </el-dialog>
      </el-aside>
      <el-container>
        <el-header>
          <div class="header-content">
            <span class="current-chat-name">
              {{ currentChatId ? (chatNames[currentChatId] || '新建对话') : 'AI 助手' }}
            </span>
            <div class="user-actions">
              <el-button type="text" @click="showUserInfo">
                <el-icon><User /></el-icon>
                个人信息
              </el-button>
              <el-button type="text" @click="handleLogout">退出登录</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <div class="chat-container">
            <!-- 空状态提示 -->
            <div v-if="!currentChatId" class="empty-state">
              <el-empty description="暂无对话">
                <template #description>
                  <p>点击左侧"新建对话"按钮开始聊天</p>
                </template>
                <el-button type="primary" size="small" @click="createNewChat">
                  新建对话
                </el-button>
              </el-empty>
            </div>

            <!-- 聊天内容区域 -->
            <template v-else>
              <ChatAi
                  :chatId="currentChatId"
                  ref="chatAiRef"
                  @create-chat="createNewChat"
              />
            </template>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElContainer, ElAside, ElHeader, ElMain, ElButton, ElMessage, ElDialog, ElInput, ElDescriptions, ElDescriptionsItem, ElForm, ElFormItem } from 'element-plus'
import { Plus, Edit, Delete, User } from '@element-plus/icons-vue'
import ChatAi from './ChatAi.vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const conversationIds = ref([])
const currentChatId = ref('')
const chatAiRef = ref(null)
const creating = ref(false)
const chatNames = ref({})
const editDialogVisible = ref(false)
const editingName = ref('')
const editingId = ref(null)
const deleteDialogVisible = ref(false)
const deletingId = ref(null)
const deleting = ref(false)
const userInfoVisible = ref(false)
const userInfo = ref(null)
const isEditing = ref(false)
const editForm = ref({})
const editFormRef = ref(null)
const saving = ref(false)
const deleteConfirmVisible = ref(false)
const deletingUser = ref(false)

const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const fetchChatName = async (conversationId) => {
  try {
    const response = await fetch(`/ai/getConversationNameById?conversationId=${conversationId}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json'
      },
      credentials: 'include'
    })
    const result = await response.json()
    if (result.code === '200' && result.data) {
      chatNames.value[conversationId] = result.data.name
    }
  } catch (error) {
    console.error('获取对话名称失败:', error)
  }
}

const fetchConversationIds = async () => {
  const userId = localStorage.getItem('userId')
  if (!userId) {
    console.log('Home组件：未检测到登录状态')
    router.push('/login')
    return
  }

  try {
    console.log('开始请求对话列表...')
    const response = await fetch(`/user/getUserConversationIdByUserId?userId=${userId}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json'
      },
      credentials: 'include'
    })

    const result = await response.json()
    console.log('对话列表响应:', result)

    if (result.code === '200') {
      conversationIds.value = Array.isArray(result.data) ? result.data : []
      if (result.data && result.data.length > 0) {
        currentChatId.value = String(result.data[0])
        console.log('设置当前对话ID:', currentChatId.value)
      } else {
        currentChatId.value = ''
      }
      // 获取所有对话的名称
      await Promise.all(conversationIds.value.map(id => fetchChatName(id)))
    } else {
      throw new Error(result.message || '获取对话列表失败')
    }
  } catch (error) {
    console.error('获取对话列表失败:', error)
    ElMessage.error('获取对话列表失败')
    conversationIds.value = []
    currentChatId.value = ''
  }
}

const fetchUserInfo = async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('未检测到登录状态')
      return
    }

    const response = await fetch(`/user/getUserById?id=${userId}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json'
      },
      credentials: 'include'
    })

    const result = await response.json()
    if (result) {
      userInfo.value = result
    } else {
      throw new Error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

const showUserInfo = async () => {
  userInfoVisible.value = true
  if (!userInfo.value) {
    await fetchUserInfo()
  }
}

const switchConversation = (id) => {
  console.log('切换到对话:', id)
  currentChatId.value = String(id)
  if (chatAiRef.value) {
    chatAiRef.value.fetchChatHistory()
  }
}

const handleLogout = () => {
  console.log('执行退出登录')
  localStorage.clear()
  router.push('/login')
}

const showEditDialog = (id) => {
  editingId.value = id
  editingName.value = chatNames.value[id] || '新建对话'
  editDialogVisible.value = true
}

const saveConversationName = async () => {
  if (!editingName.value.trim()) {
    ElMessage.warning('请输入对话名称')
    return
  }

  try {
    const response = await fetch('/ai/setConversationNameById', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        conversationId: editingId.value,
        name: editingName.value.trim()
      })
    })

    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`)
    }

    const result = await response.json()
    console.log('修改对话名称响应:', result)

    if (result.code === '200') {
      ElMessage.success('修改成功')
      chatNames.value[editingId.value] = editingName.value.trim()
      editDialogVisible.value = false
    } else {
      throw new Error(result.message || '修改失败')
    }
  } catch (error) {
    console.error('修改对话名称失败:', error)
    ElMessage.error(`修改失败: ${error.message}`)
  }
}

const createNewChat = async () => {
  try {
    creating.value = true
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('未检测到登录状态，请重新登录')
      router.push('/login')
      return
    }

    const newConversationId = `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    console.log('开始创建新对话，conversationId:', newConversationId, 'userId:', userId)

    const response = await fetch('/ai/addNewChat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      },
      body: new URLSearchParams({
        conversationId: newConversationId,
        userId: userId
      }),
      credentials: 'include'
    })

    console.log('响应状态:', response.status)
    const result = await response.json()
    console.log('创建对话响应:', result)

    if (result.code === '200') {
      ElMessage.success('创建新对话成功')
      if (!conversationIds.value) {
        conversationIds.value = []
      }
      conversationIds.value.unshift(newConversationId)
      chatNames.value[newConversationId] = '新建对话'
      currentChatId.value = newConversationId
      if (chatAiRef.value) {
        chatAiRef.value.fetchChatHistory()
      }
    } else {
      throw new Error(result.message || '创建对话失败')
    }
  } catch (error) {
    console.error('创建新对话失败:', error)
    ElMessage.error(`创建新对话失败: ${error.message}`)
  } finally {
    creating.value = false
  }
}

const showDeleteConfirm = (id) => {
  deletingId.value = id
  deleteDialogVisible.value = true
}

const confirmDelete = async () => {
  if (!deletingId.value) return

  try {
    deleting.value = true
    const response = await fetch(`/ai/deleteChat?conversationId=${deletingId.value}`, {
      method: 'DELETE',
      headers: {
        'Accept': 'application/json'
      },
      credentials: 'include'
    })

    const result = await response.json()

    if (result.code === '200') {
      ElMessage.success('删除成功')
      conversationIds.value = conversationIds.value.filter(id => id !== deletingId.value)
      delete chatNames.value[deletingId.value]

      if (currentChatId.value === deletingId.value) {
        currentChatId.value = conversationIds.value[0] || ''
        if (currentChatId.value && chatAiRef.value) {
          chatAiRef.value.fetchChatHistory()
        }
      }

      deleteDialogVisible.value = false
    } else {
      throw new Error(result.message || '删除失败')
    }
  } catch (error) {
    console.error('删除对话失败:', error)
    ElMessage.error(`删除失败: ${error.message}`)
  } finally {
    deleting.value = false
  }
}

const startEdit = () => {
  editForm.value = {
    id: userInfo.value.id,
    name: userInfo.value.name,
    account: userInfo.value.account,
    password: userInfo.value.password
  }
  isEditing.value = true
}

const cancelEdit = () => {
  isEditing.value = false
  editForm.value = {}
}

const saveUserInfo = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()
    saving.value = true

    const response = await fetch('/user/updateUserById', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify(editForm.value)
    })

    const result = await response.json()

    if (result.code === '200') {
      ElMessage.success('修改成功')
      userInfo.value = { ...editForm.value }
      isEditing.value = false
    } else {
      throw new Error(result.message || '修改失败')
    }
  } catch (error) {
    console.error('修改用户信息失败:', error)
    ElMessage.error(`修改失败: ${error.message}`)
  } finally {
    saving.value = false
  }
}

const showDeleteUserConfirm = () => {
  deleteConfirmVisible.value = true
}

const confirmDeleteUser = async () => {
  try {
    deletingUser.value = true
    const userId = userInfo.value.id

    const response = await fetch(`/user/deleteUserById?id=${userId}`, {
      method: 'DELETE',
      headers: {
        'Accept': 'application/json'
      },
      credentials: 'include'
    })

    const result = await response.json()

    if (result.code === '200') {
      ElMessage.success('账号已删除')
      deleteConfirmVisible.value = false
      userInfoVisible.value = false
      localStorage.clear()
      router.push('/login')
    } else {
      throw new Error(result.message || '删除失败')
    }
  } catch (error) {
    console.error('删除用户失败:', error)
    ElMessage.error(`删除失败: ${error.message}`)
  } finally {
    deletingUser.value = false
  }
}

const checkLoginStatus = () => {
  const userId = localStorage.getItem('userId')
  if (!userId) {
    console.log('登录状态已失效')
    router.push('/login')
    return false
  }
  return true
}

let loginCheckInterval
onMounted(async () => {
  if (!checkLoginStatus()) return

  await Promise.all([
    fetchConversationIds(),
    fetchUserInfo()
  ])

  loginCheckInterval = setInterval(checkLoginStatus, 60000)
})

onBeforeUnmount(() => {
  if (loginCheckInterval) {
    clearInterval(loginCheckInterval)
  }
})
</script>

<style scoped>
.common-layout {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
}

.el-container {
  height: 100%;
  width: 100%;
}

.el-aside {
  background-color: #f8f8f8;
  border-right: 1px solid #ddd;
  display: flex;
  flex-direction: column;
}

.aside-header {
  padding: 15px;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.conversation-list {
  overflow-y: auto;
  height: calc(100% - 50px);
  flex: 1;
}

.conversation-item {
  padding: 10px 15px;
  cursor: pointer;
  transition: background-color 0.3s;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.conversation-item:hover {
  background-color: #f5f5f5;
}

.conversation-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
}

.conversation-content {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-actions {
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  gap: 4px;
}

.conversation-item:hover .conversation-actions {
  opacity: 1;
}

.el-header {
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.current-chat-name {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  max-width: 50%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.el-main {
  padding: 0;
  background-color: #fff;
  height: 100%;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #ff4949;
}

.user-info-content {
  padding: 20px 0;
}

.el-descriptions {
  margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
  width: 100px;
  justify-content: flex-end;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

.delete-confirm-content {
  text-align: center;
  padding: 20px 0;
}

.delete-confirm-content .warning {
  color: #f56c6c;
  margin-top: 10px;
  font-size: 14px;
}

@media screen and (max-width: 768px) {
  .el-aside {
    display: none;
  }
}
</style>
